﻿using System;
using System.ComponentModel.Composition;
using CoProjectModel;
using IdeaBlade.Application.Framework.Core.Persistence;
using IdeaBlade.EntityModel;

namespace CoProjectDF.Repository
{
    [Export(typeof(IToDoItemRepository))]
    public class ToDoItemRepository : IToDoItemRepository
    {
        [ImportingConstructor]
        public ToDoItemRepository(IEntityManagerProvider<CoProjectEntities> entityManagerProvider)
        {
            EntityManagerProvider = entityManagerProvider;
        }

        private IEntityManagerProvider<CoProjectEntities> EntityManagerProvider { get; set; }

        private CoProjectEntities Manager
        {
            get { return EntityManagerProvider.Manager; }
        }

        #region IToDoItemRepository Members

        public INotifyCompleted FindToDoItemByID(int ID, Action<ToDoItem> onSuccess = null,
                                                 Action<Exception> onFail = null)
        {
            EntityScalarQueryOperation<ToDoItem> op =
                Manager.ToDoItems.Where(c => c.ToDoItemID == ID).AsScalarAsync().FirstOrDefault();
            return op.OnComplete(onSuccess, onFail);
        }

        /// <summary>
        /// For Design-Time. Gets a single TiDoItem
        /// </summary>
        /// <param name="onSuccess"></param>
        /// <param name="onFail"></param>
        /// <returns></returns>
        public INotifyCompleted GetFirstItem(Action<ToDoItem> onSuccess = null,
                                             Action<Exception> onFail = null)
        {
            EntityScalarQueryOperation<ToDoItem> op = Manager.ToDoItems.AsScalarAsync().FirstOrDefault();
            return op.OnComplete(onSuccess, onFail);
        }

        public INotifyCompleted Save(Action onSuccess = null,
                                     Action<Exception> onFail = null)
        {
            EntitySaveOperation so = Manager.SaveChangesAsync();
            return so.OnComplete(onSuccess, onFail);
        }

        #endregion
    }
}